package com.coolmusic;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private EditText etUsername, etPassword;
    private Button btnLogin, btnRegister;
    private SharedPreferences sharedPreferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initViews();
        initSharedPreferences();
        setupButtonListeners();
    }

    private void initViews() {
        etUsername = findViewById(R.id.et_username);
        etPassword = findViewById(R.id.et_password);
        btnLogin = findViewById(R.id.btn_login);
        btnRegister = findViewById(R.id.btn_register);
    }

    private void initSharedPreferences() {
        sharedPreferences = getSharedPreferences("UserPrefs", MODE_PRIVATE);
        // 检查是否有已登录用户，直接跳转主界面（优化启动流程）
        String currentUsername = sharedPreferences.getString("current_username", null);
        if (currentUsername != null) {
            openMainMusicActivity();
            finish(); // 关闭登录界面
        }
    }

    private void setupButtonListeners() {
        btnLogin.setOnClickListener(v -> validateLogin());
        btnRegister.setOnClickListener(v -> startActivity(new Intent(this, activity_register.class)));
    }

    private void validateLogin() {
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password)) {
            Toast.makeText(this, "请填写用户名和密码", Toast.LENGTH_SHORT).show();
            return;
        }

        String storedPassword = sharedPreferences.getString(username, null);
        if (storedPassword != null && storedPassword.equals(password)) {
            saveLoginState(username);
            openMainMusicActivity();
        } else {
            Toast.makeText(this, "登录失败，用户名或密码错误", Toast.LENGTH_SHORT).show();
        }
    }

    private void saveLoginState(String username) {
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("current_username", username); // 保存当前登录用户
        editor.apply(); // 异步保存，提升性能
    }

    private void openMainMusicActivity() {
        Intent intent = new Intent(this, MusicActivity.class);
        startActivity(intent);
        finish(); // 防止按返回键回到登录界面
    }
}